package common.struct;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import common.struct.State;

import java.util.List;

public class AppInfo {
    public String name;
    public boolean ctx;
    public boolean inv;
    public State state;
    public List<String> sensors;
    public List<String> actors;
    private JSONObject jo;

    public AppInfo(String name, boolean ctx, boolean inv, State state, List<String> sensors, List<String> actors) {
        this.name = name;
        this.ctx = ctx;
        this.inv = inv;
        this.state = state;
        this.sensors = sensors;
        this.actors = actors;
    }

    public AppInfo(JSONObject obj) {
        this.jo = obj;
        this.name = obj.getString("app_name");
        this.ctx = obj.getBoolean("ctx");
        this.inv = obj.getBoolean("inv");
        this.state = State.fromString(obj.getString("state"));
        this.sensors = obj.getJSONArray("sensors").toJavaList(String.class);
        this.actors = obj.getJSONArray("actors").toJavaList(String.class);
    }

    @Override
    public String toString() {
        if (jo != null) return jo.toJSONString();
        jo = new JSONObject();
        jo.put("app_name", name);
        jo.put("ctx", ctx);
        jo.put("inv", inv);
        jo.put("state", state);
        JSONArray ja = new JSONArray();
        ja.addAll(sensors);
        jo.put("sensors", ja);
        ja = new JSONArray();
        ja.addAll(actors);
        jo.put("actors", ja);
        return jo.toJSONString();
    }
}
